package msqlite

import (
	"fmt"
	"gitee.com/dennis-mxx/gcode-common/menv"
	"gitee.com/dennis-mxx/gcode-common/mlogger"
	_ "github.com/mattn/go-sqlite3"
	"time"
	"xorm.io/xorm"
)

func Initialize(logger *mlogger.TraceLogger) (*xorm.Engine, error) {
	if menv.Environment.Sqlite != nil && menv.Environment.Sqlite.Addr != "" {

		sqlite3 := menv.Environment.Sqlite
		if sqlite3.MaxIdleConn == 0 {
			sqlite3.MaxIdleConn = 5
		}
		if sqlite3.MaxOpenConn == 0 {
			sqlite3.MaxOpenConn = 600
		}
		if sqlite3.Timeout == 0 {
			sqlite3.Timeout = 30
		}

		if engine, err := ConnectionSqlite3(logger, menv.Environment.Sqlite); err == nil {
			logger.Info(fmt.Sprintf("Initialize [connection sqlite3 database [%s] successful] ", sqlite3.Addr))
			return engine, err
		} else {
			logger.Info(fmt.Sprintf("Initialize [connection sqlite3 database [%s] failure] ", sqlite3.Addr))
			return engine, err
		}
	}
	return nil, nil

}

func ConnectionSqlite3(logger *mlogger.TraceLogger, dataSource *menv.Sqlite3) (*xorm.Engine, error) {
	defer mlogger.FormatException(func() *mlogger.TraceLogger {
		return logger
	})
	engine, err := xorm.NewEngine(`sqlite3`, dataSource.Addr)
	if err == nil {
		timeout := time.Duration(dataSource.Timeout)
		engine.SetMaxOpenConns(dataSource.MaxOpenConn)        // 用于设置最大打开的连接数，默认值为0表示不限制
		engine.SetMaxIdleConns(dataSource.MaxIdleConn)        // 用于设置闲置的连接数
		engine.SetConnMaxLifetime(timeout * time.Millisecond) // 设置一个超时时间，时间小于数据库的超时时间即可
		engine.ShowSQL(dataSource.ShowSql)
	}

	return engine, err
}
